package com.yygo.service.impl;

import com.yygo.Constants;
import com.yygo.dao.BankDao;
import com.yygo.model.Bank;
import com.yygo.model.LoanProduct;
import com.yygo.model.User;
import com.yygo.service.BankManager;
import com.yygo.service.RoleManager;
import com.yygo.service.UserExistsException;
import com.yygo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * Created by tiansha on 2015/8/6.
 */
@Service("bankManager")
public class BankManagerImpl extends GenericManagerImpl<Bank, Long> implements BankManager {

    private BankDao bankDao;

    @Autowired
    private UserManager userManager;
    @Autowired
    private RoleManager roleManager;

    @Autowired
    public BankManagerImpl(BankDao bankDao) {
        super(bankDao);
        this.bankDao = bankDao;
    }

    @Override
    public List<Bank> getAllBanks() {
        return bankDao.getAllBanks();
    }

    @Override
    public Set<LoanProduct> getLoanProductsByBank(Long bankId) {
        return bankDao.getLoanProductsByBank(bankId);
    }

    @Override
    public void saveBank(Bank bank) throws UserExistsException {
        User user = bank.getBankUser();
        user.setEnabled(true);
        user.getRoles().clear();
        user.addRole(roleManager.getRole(Constants.Bank_USER_ROLE));
        user.addRole(roleManager.getRole(Constants.Bank_ADMIN_ROLE));
        User adminUser = userManager.saveUser(user);
        bank.setBankUser(adminUser);
        save(bank);
    }

    @Override
    public List<User> getUsers(Long bankId) {
        return bankDao.getUsers(bankId);
    }
}
